package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: sky-take-out
 * @description:
 * @author: fmp
 * @create: 2023-04-09 15:10
 * @Version 1.0
 **/

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    private final static String KEY = "DISH" ;
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetMealDishMapper setMealDishMapper;
    @Resource
    private RedisTemplate redisTemplate;
    //菜品分页查询
    @Override
    public PageResult SelectedDishPageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> result =dishMapper.SelectedDishPageQuery(dishPageQueryDTO);

        return  PageResult.builder().total(result.getTotal()).records(result.getResult()).build();
    }


    //修改菜品
    @Override
    @Transactional
    @CacheEvict(cacheNames = "DISH",allEntries = true)
    public void updateDish(DishDTO dishDTO) {
        //修改dish表的菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);
        //修改dish_flavor表中的菜品信息
        //根据id删除口味信息
             dishFlavorMapper.deleteByUId(dish.getId());
        if (dishDTO.getFlavors() != null&&dishDTO.getFlavors().size()>0) {
            dishDTO.getFlavors().forEach(flavor -> flavor.setDishId(dish.getId()));
            List<DishFlavor> flavors = dishDTO.getFlavors();
            dishFlavorMapper.insertDishList(flavors);
        }
    }
    //根据id查询
    @Override
    public DishVO SelectedDishById(Long id) {
        Dish dish= dishMapper.SelectedDishById(id);
        List<DishFlavor> dishFlavor =dishFlavorMapper.SelectedDishById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }
    //新增菜品
    @Override
    @Transactional
    @CacheEvict(cacheNames = KEY,allEntries = true)
    public void insertDish(DishDTO dishDTO) {
        //增加dish表的菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.ENABLE);
        //返回一个对象,主键的id（配合新增）
        dishMapper.insertDish(dish);
        log.info("==========返回id{}",dish.getId());
        //增加dish_flavor表中的菜品信息
        if(!Objects.isNull(dishDTO.getFlavors())&&dishDTO.getFlavors().size()>0) {
            dishDTO.getFlavors().forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            List<DishFlavor> flavor = dishDTO.getFlavors();
            dishFlavorMapper.insertDishList(flavor);
        }
    }
    //根据id批量删除
    @Override
    @Transactional
    @CacheEvict(cacheNames = KEY,allEntries = true)
    public void deleteDishById(List<Long> ids) {
        for (Long id : ids) {
            //根据启售状态查询返回
            Dish dish = dishMapper.SelectedDishById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
          Long count =  setMealDishMapper.selectedById(ids);
            if (count>0){
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
            }
        }
        dishMapper.deleteDishById(ids);
        dishFlavorMapper.deleteDishById(ids);
    }
    //根据菜品分类id查询

    @Override
    public List<Dish> SelectedDishByCategoryId(Long categoryId) {
        List<Dish>  dishList = dishMapper.SelectedDishByCategoryId(categoryId);
        return dishList;
    }

    /**
     * 查询指定分类菜品和口味
     *
     * @param categoryId 分类Id
     * @return 菜品基本信息 + 菜品的口味信息的集合
     */
    @Override
    public List<DishVO> selectDishAndFlavorByCategoryId(Long categoryId) {
        //调用持久层查询所有该分类启售菜品的信息
        List<Dish> dishList = dishMapper.selectStatus1DishByCategoryId(categoryId);
        return dishList.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO); //将Dish中的基础信息拷贝到DishVO
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectDishFlavorByDishId(dish.getId());
            dishVO.setFlavors(dishFlavorList);
            return dishVO;
        }).collect(Collectors.toList());
    }

}
